﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using QT.Windows.Shell;

namespace UrlChecker.Tools
{
    public partial class Keywords : GlassForm
    {
        #region Attributes

        private Thread myThread = null;
        private delegate string myDeleGategetURL();
        private delegate string myDeleGategetPage();
        private delegate void myDeleGateshowResult(ListViewItem item);
        private delegate void myDeleGateshowMsg(string txt);

        Regex regex = new Regex(@"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase);
        private string keywords = "";

        #endregion

        #region Keywords

        public Keywords()
        {
            InitializeComponent();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            e.Cancel = true;
            if (myThread != null && myThread.IsAlive)
            {
                if (MessageBox.Show("正在进行关键字检查，确认要关闭吗？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel) return;
                myThread.Abort();
            }
            e.Cancel = false;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            this.statusStrip1.BackColor = AeroColor;
        }

        #endregion

        #region Event

        #region GlassButton

        private void gbtnSearch_Click(object sender, EventArgs e)
        {
            if (this.tbUrl.Text.Length == 0)
            {
                MessageBox.Show("请输入网址");
                return;
            }
            if (!regex.IsMatch(this.tbUrl.Text))
            {
                MessageBox.Show("网址格式不正确");
                return;
            }
            if (this.tbKeywords.Text.Length == 0)
            {
                MessageBox.Show("请输入关键字");
                return;
            }
            Regex reg = new Regex(@"\d+");
            if(this.cbPage.Checked&&(!reg.IsMatch(this.tbPage.Text)))
            {
                MessageBox.Show("请输入正确的页码");
                return;
            }

            keywords = this.tbKeywords.Text;

            myThread = new Thread(new ThreadStart(ThreadSearch));
            myThread.Start();
        }

        #endregion

        #endregion

        #region Thread

        private void ThreadSearch()
        {
            string[] keywords = this.tbKeywords.Text.Replace(" ", "|").Replace(";", "|").Split('|');
            string[] SearchEngines = QT.SEO.Setting.Get("SearchEngine").Split('|');
            string InterVal = QT.SEO.Setting.Get("InterVal");

            foreach (string SearchEngine in SearchEngines)
            {
                DataTable dt = QT.SEO.SearchEngine.Get(SearchEngine);
                string myURI = dt.Rows[0]["uri"].ToString();
                int codepage = 0;
                if (!(int.TryParse(dt.Rows[0]["codepage"].ToString(), out codepage))) codepage = 0;
                int pagecount = getPage() == null ? 1 : int.Parse(getPage());
                string ref_url = "";
                string url = "";
                dt.Dispose();
                foreach (string keyword in keywords)
                {
                    bool b = true;
                    ref_url = url;
                    url = myURI.Replace("{keywords}",System.Web.HttpUtility.UrlEncode(keyword));
                    int pageno = 0;
                    QT.SEO.KeywordResult keywordResult = new QT.SEO.KeywordResult();
                    while (b && pageno < pagecount)
                    {
                        pageno++;
                        ShowMsg(string.Format("当前进度：[{0}]{1} 第{2}页", keyword, dt.Rows[0]["SearchName"].ToString(), pageno));
                        string HtmlData = QT.SEO.UrlGather.GetHtml(url, ref_url, Encoding.GetEncoding(codepage)).Replace(" ", "").Replace("\n", "").Replace("\r", "");
                        keywordResult = QT.SEO.UrlGather.GetKeyword(HtmlData, dt.Rows[0], getURL(), Encoding.GetEncoding(codepage));
                        if (int.Parse(keywordResult.id) > 0)
                        {
                            keywordResult.page = pageno.ToString();
                            b = false;
                            break;
                        }

                        #region 设置下一页参数

                        ref_url = url;
                        url = new Regex(dt.Rows[0]["PageRegex"].ToString()).Match(HtmlData).Groups["url"].Value;
                        if (url.StartsWith("/"))
                        {
                            url = new Regex(@"http://([\w-]+\.)+[\w-]+").Match(ref_url).Value + url;
                        }

                        #endregion

                        Thread.Sleep(int.Parse(InterVal) * 1000);
                    }

                    #region 输出结果

                    ListViewItem item = new ListViewItem("0");
                    item.SubItems.Add(keyword);
                    item.SubItems.Add(dt.Rows[0]["SearchName"].ToString());
                    item.SubItems.Add(string.Format("{0}({1})", keywordResult.id, keywordResult.page));
                    if (keywordResult.id == "0") item.ForeColor = Color.Red;
                    ShowResult(item);

                    #endregion
                }
            }

            ShowMsg("完成");
        }

        #endregion

        #region Method

        private string getURL()
        {
            if (this.InvokeRequired)
            {
                return this.Invoke(new myDeleGategetURL(getURL)) as string;
            }
            else
            {
                return this.tbUrl.Text;
            }
        }

        private string getPage()
        {
            if (this.InvokeRequired)
            {
                return this.Invoke(new myDeleGategetPage(getPage)) as string;
            }
            else
            {
                if (this.cbPage.Checked) return this.tbPage.Text;
                else return "1";
            }
        }

        private void ShowResult(ListViewItem item)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new myDeleGateshowResult(ShowResult), new object[] { item });
            }
            else
            {
                item.Text = (this.lvResult.Items.Count + 1).ToString();
                this.lvResult.Items.Add(item);
            }
        }

        private void ShowMsg(string txt)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new myDeleGateshowMsg(ShowMsg), new object[] { txt });
            }
            else
            {
                this.tsslMsg.Text = txt;
            }
        }

        #endregion
    }
}
